/**
 * @Title: index.js
 * @Description: index
 * @author: Fanchao
 * @date: 2020/9/19 3:59 下午
 * @version V1.0
 */
import React from 'react';
import { connect, Link } from 'umi';
import styles from './index.less';
import { Button, Form, Input, Table, Select, message } from 'antd';
import moment from 'moment';
import { reqUpdateProduct } from 'api/index';

const { Option } = Select;
const Product = ({ adoptProductList: { dataSource, keyword, limit, offset, breedList, breed }, dispatch, loading }) => {
    const [form] = Form.useForm();
    const resold = () => {
        dispatch({
            type: 'adoptProductList/getProductList',
            payload: {
                keyword: '',
                limit: 10,
                offset: 0,
                breed: '',
            },
        });
    };
    const search = () => {
        form.validateFields().then(values => {
            const { keyword, breed } = values;
            dispatch({
                type: 'adoptProductList/getProductList',
                payload: {
                    keyword,
                    limit,
                    offset,
                    breed,
                },
            });
        });
    };
    const empty = () => {
        form.resetFields();
        resold();
    };
    const searchByOffset = (offset) => {
        dispatch({
            type: 'adoptProductList/getProductList',
            payload: {
                keyword,
                limit,
                offset: offset - 1,
                breed,
            },
        });
    };
    const setProductStatus = (item) => {
        const params = {
            id: item._id,
            status: item.status === 1 ? 0 : 1,
        };
        dispatch({
            type: 'adoptProductList/updateProduct',
            payload: params,
            callback: (res) => {
                resold();
            },
        });
    };
    const deleteProduct = (item) => {
        dispatch({
            type: 'adoptProductList/removeProduct',
            payload: {
                id: item._id,
            },
            callback: (response) => {
                resold();
            },
        });
    };
    const setHot = async (item) => {
        const { hot, _id } = item;
        const params = {
            id: _id,
            hot: !hot,
        };
        const result = await reqUpdateProduct(params);
        if (result.status === 1) {
            resold();
        } else {
            message.error(result.message);
        }
    };
    const setRecommend = async (item) => {
        const { recommend, _id } = item;
        const params = {
            id: _id,
            recommend: !recommend,
        };
        const result = await reqUpdateProduct(params);
        if (result.status === 1) {
            resold();
        } else {
            message.error(result.message);
        }
    };
    const columns = [
        {
            title: '商品',
            align: 'left',
            render: (item) => {
                return (
                    <div>
                        <img style={{ width: '40px', height: '40px', marginRight: '10px' }}
                             src={item.spec_items[0].thumbnail} alt=""/>
                        {item.spec_items[0].pname}
                    </div>
                );
            },
        },
        {
            title: '商品分类',
            dataIndex: 'category_name',
            align: 'left',
        },
        {
            title: '商品服务',
            dataIndex: 'tags',
            align: 'left',
        },
        {
            title: '现价',
            align: 'left',
            render: (item) => item.spec_items[0].price,
        },
        {
            title: '原价',
            align: 'left',
            render: (item) => item.spec_items[0].original_price,
        },
        {
            title: '产地',
            dataIndex: 'origin_place',
            align: 'left',
        },
        {
            title: '库存',
            align: 'left',
            render: (item) => item.spec_items[0].stock,
        },
        {
            title: '是否热门',
            align: 'left',
            dataIndex: 'hot',
            render: (hot) => hot ? '是' : '否',
        },
        {
            title: '是否推荐',
            align: 'left',
            dataIndex: 'recommend',
            render: (recommend) => recommend ? '是' : '否',
        },
        {
            title: '状态',
            dataIndex: 'status',
            align: 'left',
            render: (status) => {
                let statusHtml = '';
                switch (status) {
                    case 0 :
                        statusHtml = '已上架';
                        break;
                    case 1 :
                        statusHtml = '已下架';
                        break;
                    default :
                        statusHtml = '--';
                }
                return (
                    <div>
                        {statusHtml}
                    </div>
                );
            },
        },
        {
            title: '创建时间',
            dataIndex: 'created_time',
            align: 'left',
            render: (created_time) => moment(created_time).format('YYYY-MM-DD hh:mm:ss'),
        },
        {
            title: '操作',
            align: 'left',
            render: (item) => {
                return (
                    <div>
                        <Button type="link" onClick={() => setHot(item)}>设为热门</Button>
                        <Button type="link" onClick={() => setRecommend(item)}>设为推荐</Button>
                        <Link to={{
                            pathname: '/product-manage/adopt-product/edit',
                            state: { fromDashboard: true },
                            query: { id: item._id },
                        }} style={{ marginRight: '10px' }}>编辑</Link>
                        <Link to={{
                            pathname: '/product-manage/adopt-product/detail',
                            state: { fromDashboard: true },
                            query: { id: item._id },
                        }} style={{ marginRight: '10px' }}>详情</Link>
                        <Button type="link"
                                style={{ padding: '0' }}
                                onClick={() => setProductStatus(item)}>{item.status === 1 ? '上架' : '下架'}</Button>
                        <Button type="link" onClick={() => deleteProduct(item)}>删除</Button>
                    </div>
                );
            },
        },
    ];
    return (
        <div className={styles.pageContainer}>
            <div className={styles.pageContainerFilter}>
                <Form
                    layout="inline"
                    form={form}
                >
                    <Form.Item
                        label="关键字"
                        name="keyword"
                    >
                        <Input placeholder="商品名称"/>
                    </Form.Item>
                    <Form.Item
                        label="品种"
                        name="breed"
                    >
                        <Select
                            placeholder="请选择分类"
                        >
                            {
                                breedList.map(item => <Option key={item.label} value={item.label}>{item.label}</Option>)
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" style={{ marginRight: '16px' }} onClick={search}>查询</Button>
                        <Button type="primary" onClick={empty}>清空</Button>
                    </Form.Item>
                </Form>
            </div>
            <div className={styles.pageContainerTable}>
                <Table
                    bordered={false} // 是否有边框
                    rowKey='_id' // 唯一key值
                    loading={loading} // 加载动画
                    columns={columns} // 表头
                    dataSource={dataSource.list}
                    pagination={{
                        total: dataSource.total,// 总记录数
                        defaultPageSize: 10, // 默认显示条数
                        showQuickJumper: true, // 快速跳转
                        // showSizeChanger: true, // 一页展示数据条数
                        onChange: (offset) => searchByOffset(offset),
                        showTotal: () => {
                            return `共${dataSource.total}条`;
                        },
                    }}
                />
            </div>
        </div>
    );
};

export default connect(({ adoptProductList, dispatch, loading }) => ({
    adoptProductList,
    dispatch,
    loading: loading.effects['adoptProductList/getProductList'],
}))(Product);
